import 'package:flutter/material.dart';
import 'dart:async';

class NoticeBar extends StatefulWidget {
  @override
  _NoticeBarState createState() => _NoticeBarState();
}

class _NoticeBarState extends State<NoticeBar> with WidgetsBindingObserver {
  GlobalKey _myKey = new GlobalKey();
  ScrollController _controller;
  int index = 0;

  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  void initState() {
    //来监听 节点是否build完成
    WidgetsBinding widgetsBinding = WidgetsBinding.instance;
    widgetsBinding.addPostFrameCallback((callback) {
      Timer.periodic(new Duration(seconds: 5), (timer) {
        index += _myKey.currentContext.size.height.toInt();
        _controller.animateTo((index).toDouble(),
            duration: new Duration(seconds: 1), curve: Curves.easeOutSine);
        //滚动到底部从头开始
        if ((index - _myKey.currentContext.size.height.toInt()).toDouble() >
            _controller.position.maxScrollExtent) {
          _controller.jumpTo(_controller.position.minScrollExtent);
          index = 0;
        }
      });
    });
    _controller = new ScrollController(initialScrollOffset: 0);
    /*   _controller.addListener(() {
      print(_controller.offset);
    });*/
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 22,
      margin: EdgeInsets.fromLTRB(0, 10, 0, 0),
      child: ListView.builder(
          key: _myKey,
          //禁止手动滑动
          physics: new NeverScrollableScrollPhysics(),
          itemCount: 5,
          //item固定高度
          itemExtent: 22.0,
          scrollDirection: Axis.vertical,
          controller: _controller,
          itemBuilder: (context, index) {
            return GestureDetector(
              onTap: (){Navigator.pushNamed(context, '/notice');},
              child: Container(
                alignment: Alignment.centerLeft,
                child: Text(
                  " 春节期间\"财富 \"和\"趋势\"产品排期公告 " + index.toString(),
                  style: TextStyle(fontSize: 14, fontWeight: FontWeight.w500),
                ),
              ),
            );
          }),
    );
  }
}
